package cn.edu.tsinghua.weibo.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;
import cn.edu.tsinghua.weibo.action.WeiboAction;
import cn.edu.tsinghua.weibo.entity.User;
import cn.edu.tsinghua.weibo.util.ContentFilter;
import cn.edu.tsinghua.weibo.util.DB;
import cn.edu.tsinghua.weibo.util.FormateDate;

@SuppressWarnings("serial")
public class Publish extends HttpServlet {

	private static final String SQL_INSERT = "insert into weibo(content, time, userid, client, forwardid, picture) values(?, ?, ?, ?, ?, ?)";
	private static final String SQL_QUERY = "select w.id weiboid, w.content, w.time, w.client, w.forwardid, w.picture, u.id userid, u.nick, u.avatar" +
											" from weibo w, user u" +
											" where w.userid=u.id and u.id=?" +
											" order by weiboid desc";//按weibo id的降序排序，以便取得刚刚发表的这一条weibo

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String content = request.getParameter("content");
		int forwardid = Integer.parseInt(request.getParameter("forwardid"));
		String picture = request.getParameter("picture");
		HttpSession session = request.getSession();
		int userid = ((User)session.getAttribute("user")).getId();
		Timestamp time = new Timestamp(System.currentTimeMillis());
		try {
			Connection connection = DB.getConnection();
			PreparedStatement preparedStatement = connection.prepareStatement(SQL_INSERT);
			preparedStatement.setString(1, content);
			preparedStatement.setTimestamp(2, time);
			preparedStatement.setInt(3,  userid);
			preparedStatement.setString(4, request.getRemoteHost());
			if (forwardid == -1) {
				preparedStatement.setNull(5, Types.INTEGER);
			} else {
				preparedStatement.setInt(5, forwardid);
			}
			if (picture == "-1") {
				preparedStatement.setNull(6, Types.VARCHAR);
			} else {
				preparedStatement.setString(6, picture);
			}
			preparedStatement.executeUpdate();

			preparedStatement = connection.prepareStatement(SQL_QUERY);
			preparedStatement.setInt(1, userid);
			ResultSet resultSet = preparedStatement.executeQuery();
			resultSet.next();//next之后就是第一条
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userid", resultSet.getInt("userid"));
			map.put("weiboid", resultSet.getInt("weiboid"));
			map.put("content", ContentFilter.getFiltratedContent(resultSet.getString("content")));
			map.put("time", FormateDate.getFormattedDate(resultSet.getTimestamp("time").getTime()));
			map.put("client", resultSet.getString("client"));
			map.put("forwardid", resultSet.getInt("forwardid"));
			map.put("picture", resultSet.getString("picture"));
			if(resultSet.getInt("forwardid") != 0) {
				Map<String, Object> forwardinfo = WeiboAction.getForwardInfo(resultSet.getInt("forwardid"));
				map.put("allComments", forwardinfo.get("allComments"));
				Object[] primeWeibo = (Object[]) forwardinfo.get("primeWeibo");
				if(primeWeibo != null) {
					map.put("sourceWeibo", 1);
					map.put("fweiboid", primeWeibo[0]);
					map.put("fcontent", primeWeibo[1]);
					map.put("ftime", primeWeibo[2]);
					map.put("fuserid", primeWeibo[3]);
					map.put("fnick", primeWeibo[4]);
					map.put("favatar", primeWeibo[5]);
					map.put("fclient", primeWeibo[6]);
					map.put("fpicture", primeWeibo[7]);
				} else {
					map.put("sourceWeibo", 0);
				}
			}
			map.put("nick", resultSet.getString("nick"));
			map.put("avatar", resultSet.getString("avatar"));
			
			DB.close(resultSet, preparedStatement, connection);
			
			JSONObject jsonObject = JSONObject.fromObject(map);
//			JSONArray jsonArray = JSONArray.fromObject(map);
			response.setContentType("text/html; charset=utf-8");  
			response.getWriter().print(jsonObject);
			
//			System.out.println(jsonObject);//.
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
